package cn.peng.stu4teach.util;

import android.widget.ImageView;

import androidx.annotation.DrawableRes;
import androidx.annotation.RawRes;

import com.blankj.utilcode.util.SizeUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;

import cn.peng.stu4teach.R;

/**
 * Glide 加载图片时使用的工具类
 */
public class GlideUtil {
    private static final GlideUtil ourInstance = new GlideUtil();

    private GlideUtil () {
    }

    public static GlideUtil instance () {
        return ourInstance;
    }

    /**
     * 使用 glide 加载图片
     *
     * @param radius 图片圆角半径,单位dp
     */
    public void load (ImageView pIv, String imgSrc, int placeholder, int errorImg, int radius) {
        // 定义附件选项
        RequestOptions options = new RequestOptions()
                                         .error(errorImg)
                                         .diskCacheStrategy(DiskCacheStrategy.ALL)
                                         .fitCenter()
                                         .placeholder(placeholder);
        if (radius > 0) {
            options = options.transform(new CenterCrop(), new RoundedCorners(SizeUtils.dp2px(radius)));
        }
        // 加载图片资源到 iv
        Glide.with(pIv.getContext()).load(imgSrc).apply(options).into(pIv);
    }

    /**
     * 使用 glide 加载图片
     */
    public void load (ImageView pIv, String imgSrc, int placeholder, int errorImg) {
        load(pIv, imgSrc, placeholder, errorImg, 0);
    }

    /**
     * 使用 glide 加载图片
     */
    public void load (ImageView pIv, String imgSrc) {
        load(pIv, imgSrc, R.drawable.ic_launcher, R.drawable.ic_launcher);
    }


    /**
     * 使用 glide 加载图片
     */
    public void load (ImageView pIv, @RawRes @DrawableRes Integer imgSrc, int placeholder, int errorImg, int radius) {
        // 定义附件选项
        RequestOptions options = new RequestOptions()
                                         .error(errorImg)
                                         .diskCacheStrategy(DiskCacheStrategy.ALL)
                                         .fitCenter()
                                         .placeholder(placeholder);
        if (radius > 0) {
            options = options.transform(new CenterCrop(), new RoundedCorners(SizeUtils.dp2px(radius)));
        }
        // 加载图片资源到 iv
        Glide.with(pIv.getContext()).load(imgSrc).apply(options).into(pIv);
    }

    /**
     * 使用 glide 加载图片
     */
    public void load (ImageView pIv, @RawRes @DrawableRes Integer imgSrc, int placeholder, int errorImg) {
        load(pIv, placeholder, imgSrc, errorImg, 0);
    }

    /**
     * 使用 glide 加载图片
     */
    public void load (ImageView pIv, @RawRes @DrawableRes Integer imgSrc) {
        load(pIv, imgSrc, R.drawable.ic_launcher, R.drawable.ic_launcher);
    }
}
